package com.xcx.robot.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.nlp.v20190408.NlpClient;
import com.tencentcloudapi.nlp.v20190408.models.ChatBotRequest;
import com.tencentcloudapi.nlp.v20190408.models.ChatBotResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author: 邢晨旭
 * @Date: 2021/7/5 09:05
 * @Description:
 */
@Component
@Slf4j
public class ChatBot {

    @Value("${tencent.secret.id}")
    String secretId;
    @Value("${tencent.secret.key}")
    String secretKey;

    public String talk(String msg) {
        log.info("触发聊天信息{}",msg);
        if(StringUtils.isEmpty(msg)){
            return "";
        }
        try {
            Credential cred = new Credential(secretId, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("nlp.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            NlpClient client = new NlpClient(cred, "ap-guangzhou", clientProfile);
            ChatBotRequest req = new ChatBotRequest();
            req.setQuery(msg);
            ChatBotResponse resp = client.ChatBot(req);
            String jsonStr = ChatBotResponse.toJsonString(resp);
            String reply = JSONObject.parseObject(jsonStr).getString("Reply");
            if(StringUtils.isNotEmpty(reply)){
                return reply;
            }
        } catch (Exception e) {
            log.error("腾讯闲聊异常{}",e);
        }
        return null;
    }
}
